package com.btex.app.pager;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.btex.app.Config;
import com.btex.app.R;
import com.btex.app.entity.FuturesInfo;
import com.btex.app.entity.PositionsInfo;
import com.btex.app.treaty.HistoryActivity;
import com.btex.app.treaty.PositionsAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/8/13
 * @time 下午2:29
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */

public class PositionsFragment extends Fragment {


    Unbinder unbinder;
    @BindView(R.id.activity_entrust_history)
    RecyclerView mActivityEntrustHistory;
    @BindView(R.id.fragment_swip_lishi)
    SwipeRefreshLayout mFragmentSwipLishi;
    private PositionsAdapter mOrderHisInfoAdapter;
    private String type = "1";
    private String mSettle_anchor;
    private String mIsreverse;
    private int page = 1;
    private String mSa_float_num;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View inflate = inflater.inflate(R.layout.activity_entrust_history, null);


        unbinder = ButterKnife.bind(this, inflate);
        return inflate;

    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        EventBus.getDefault().register(this);
        initRecy();
        HistoryActivity historyActivity = (HistoryActivity) getActivity();

        type = historyActivity.mType;

        getMxCcontracts(type);

        if (mFragmentSwipLishi != null) {
            mFragmentSwipLishi.setRefreshing(true);
            mFragmentSwipLishi.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    get_my_orders_his(type);

                }
            });
        }

    }

    private void initRecy() {
        mActivityEntrustHistory.setLayoutManager(new LinearLayoutManager(getActivity()));
        mOrderHisInfoAdapter = new PositionsAdapter();
        mActivityEntrustHistory.setAdapter(mOrderHisInfoAdapter);
        mOrderHisInfoAdapter.setEnableLoadMore(true);
        mOrderHisInfoAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                getMxCcontracts(type);

            }
        }, mActivityEntrustHistory);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

        EventBus.getDefault().unregister(this);

    }


    private void get_my_orders_his(final String refreshType) {
        int num = (int) ((Math.random() * 9 + 1) * 100000);

        OkGo.<String>get(Config.GET_MY_POSITIONS_HIS + "?rnd=" + String.valueOf(num)).params("contract_id", refreshType).params("page", String.valueOf(page)).params("page_size", "10").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();

                if (mFragmentSwipLishi != null) {
                    mFragmentSwipLishi.setRefreshing(false);
                }

                Log.i("vbxnbcjshdj", result);

                try {

                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {
                        //my_orders_his
                        setMyOrderHis(result);

                    } else {
                        if (mActivityEntrustHistory != null && mOrderHisInfoAdapter != null) {
                            mOrderHisInfoAdapter.setNewData(null);
                            mOrderHisInfoAdapter.setEmptyView(R.layout.item_history_empty, mActivityEntrustHistory);
                            mActivityEntrustHistory.setAdapter(mOrderHisInfoAdapter);
                        }

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        });


//
//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addQueryStringParameter("contract_id", refreshType);
//        params.addQueryStringParameter("page", String.valueOf(page));
//        params.addQueryStringParameter("page_size", "10");
//
//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MY_POSITIONS_HIS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                if (mFragmentSwipLishi != null) {
//                    mFragmentSwipLishi.setRefreshing(false);
//                }
//
//                Log.i("vbxnbcjshdj", responseInfo.result);
//
//                try {
//
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//                        //my_orders_his
//                        setMyOrderHis(responseInfo.result);
//
//                    } else {
//                        if (mActivityEntrustHistory != null && mOrderHisInfoAdapter != null) {
//                            mOrderHisInfoAdapter.setNewData(null);
//                            mOrderHisInfoAdapter.setEmptyView(R.layout.item_history_empty, mActivityEntrustHistory);
//                            mActivityEntrustHistory.setAdapter(mOrderHisInfoAdapter);
//                        }
//
//                    }
//
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//            }
//
//        });


    }


    private void setMyOrderHis(String result) {


        Log.i("lwidjqowdiqiwo", result);

        Gson gson = new Gson();
        PositionsInfo dealInfo = gson.fromJson(result, PositionsInfo.class);
        List<PositionsInfo.DataBean.PositionListsBean> position_lists = dealInfo.getData().getPosition_lists();

//       Log.i("eifwoejfwioe", size + "");

        if (position_lists.size() == 0) {

            if (page > 1) {

                mOrderHisInfoAdapter.loadMoreEnd();


            } else {
                if (mActivityEntrustHistory != null && mOrderHisInfoAdapter != null) {
                    position_lists.clear();
                    mOrderHisInfoAdapter.setNewData(position_lists);
                    mOrderHisInfoAdapter.setEmptyView(R.layout.item_history_empty, mActivityEntrustHistory);
                    mActivityEntrustHistory.setAdapter(mOrderHisInfoAdapter);
                }
            }


        } else {

            if (page > 1) {

                if (mActivityEntrustHistory != null && mOrderHisInfoAdapter != null) {
                    mOrderHisInfoAdapter.setDanwei(mSettle_anchor);
                    mOrderHisInfoAdapter.setNumber(mSa_float_num);
                    mOrderHisInfoAdapter.loadMoreComplete();
                    mOrderHisInfoAdapter.addData(position_lists);
                }

            } else {
                if (mActivityEntrustHistory != null && mOrderHisInfoAdapter != null) {
                    mOrderHisInfoAdapter.setDanwei(mSettle_anchor);
                    mOrderHisInfoAdapter.setNumber(mSa_float_num);
                    mOrderHisInfoAdapter.setNewData(position_lists);
                }
            }


        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void PositionsFragment(String event) {


        if ("HistoryDialog".equals(event)) {
            type = Config.CONTRACT_ID;
            if (mFragmentSwipLishi != null) {
                mFragmentSwipLishi.setRefreshing(true);
            }
            page = 1;
            getMxCcontracts(type);
        }

    }

    private void getMxCcontracts(final String type) {

        int num = (int) ((Math.random() * 9 + 1) * 100000);

        OkGo.<String>get(Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num)).params("contract_id", type).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {

                String result = response.body().toString();
                Log.i("mgfubvjsjhdjshdsjhdygu", result);

                try {

                    JSONObject jsonObj = new JSONObject(result);
                    if (jsonObj.getString("code").equals("1")) {

                        Gson gson = new Gson();
                        FuturesInfo futuresInfo = gson.fromJson(result, FuturesInfo.class);
                        mSettle_anchor = futuresInfo.getData().getSettle_anchor();
                        mIsreverse = futuresInfo.getData().getIsreverse();
                        mSa_float_num = futuresInfo.getData().getSa_float_num();
                        get_my_orders_his(type);

                    } else {

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });



//        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
//        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
//        RequestParams params = new RequestParams();
//        params.addHeader("app-version", Config.VERSION);
//        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
//        params.addHeader("my-client", "android");
//        params.addQueryStringParameter("contract_id", type);
//        params.addQueryStringParameter("page", String.valueOf(page));
//        params.addQueryStringParameter("page_size", "7");
//
//
//        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                Log.i("mgfubvjsjhdjshdsjhdygu", responseInfo.result);
//
//                try {
//
//                    JSONObject jsonObj = new JSONObject(responseInfo.result);
//                    if (jsonObj.getString("code").equals("1")) {
//
//
//                        Gson gson = new Gson();
//                        FuturesInfo futuresInfo = gson.fromJson(responseInfo.result, FuturesInfo.class);
//                        mSettle_anchor = futuresInfo.getData().getSettle_anchor();
//                        mIsreverse = futuresInfo.getData().getIsreverse();
//                        mSa_float_num = futuresInfo.getData().getSa_float_num();
//                        get_my_orders_his(type);
//
//                    } else {
//
//                    }
//
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//
//            }
//
//        });

    }


}
